package com.example.ywj.toutiao;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.example.ywj.toutiao.bean.Key;
import com.example.ywj.toutiao.utils.Constant;
import com.example.ywj.toutiao.utils.GridView_BaseAdapter;
import com.example.ywj.toutiao.utils.ResponseApi;
import com.example.ywj.toutiao.utils.Util;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.myDialog.MyAlertDialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class SearchActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "SearchActivity";
    private String baseUrl = Constant.BASEURL;
    @BindView(R.id.search_back)
    public TextView search_back;
    @BindView(R.id.search_fdj)
    public TextView search_fdj;
    @BindView(R.id.search_editView)
    public EditText search_editText;
    @BindView(R.id.search_gridView1)
    public GridView search_gridview1;
    @BindView(R.id.search_gridView2)
    public GridView search_gridview2;
    @BindView(R.id.search_xiala)
    public TextView search_xiala;
    @BindView(R.id.search_lajitong)
    public TextView search_lajitong;
    @BindView(R.id.search_gridView3)
    public GridView search_gridview3;
    @BindView(R.id.search_eye2)
    public TextView search_eye;
    @BindView(R.id.search_eye)
    public TextView search_eye2;
    @BindView(R.id.search_text)
    public TextView search_text;
    List<Key> listNew;
    List<Key> list;
    List<Key> list2;
    List<Key> ListNew2;
    List<Key> listNew3;
    List<Key> list3;
    public Boolean flag = true;
    public Boolean flag2 = true;
    public GridView_BaseAdapter gridView_baseAdapter;
    public GridView_BaseAdapter gridView_baseAdapter2;
    public GridView_BaseAdapter gridView_baseAdapter3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        //listNew.clear();
        initView();
        Intent intent = getIntent();
        String key =  intent.getStringExtra("key");
        Log.i(TAG, "onCreate: "+key);
        search_editText.setHint(key);
        getKeyData();
        getKeyData2();
        getKeyData3();
    }
    public void initView(){
        final Typeface font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        search_back.setTypeface(font);
        search_back.setText(getResources().getString(R.string.back));
        search_back.setOnClickListener(this);
        search_fdj.setTypeface(font);
        search_fdj.setText(getResources().getString(R.string.font5));
        search_xiala.setTypeface(font);
        search_lajitong.setTypeface(font);
        search_xiala.setText(getResources().getString(R.string.xiala));
        search_lajitong.setText(getResources().getString(R.string.lajitong));
        search_eye.setTypeface(font);
        search_eye.setText(getResources().getString(R.string.eye2));
        search_text.setOnClickListener(this);
        search_lajitong.setOnClickListener(this);
        search_eye.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(flag){
                    search_gridview3.setVisibility(View.GONE);
                    search_eye.setText(getResources().getString(R.string.eye));
                    search_eye2.setText("显示推荐词");
                    flag = false;
                }else {
                    search_gridview3.setVisibility(View.VISIBLE);
                    search_eye.setText(getResources().getString(R.string.eye2));
                    search_eye2.setText("隐藏推荐词");
                    flag = true;
                }
            }
        });
        search_eye2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(flag){
                    search_gridview3.setVisibility(View.GONE);
                    search_eye.setText(getResources().getString(R.string.eye));
                    search_eye2.setText("显示推荐词");
                    flag = false;
                }else {
                    search_gridview3.setVisibility(View.VISIBLE);
                    search_eye.setText(getResources().getString(R.string.eye2));
                    search_eye2.setText("隐藏推荐词");
                    flag = true;
                }
            }
        });
    }
    @Override
    protected void onPause() {
        overridePendingTransition(0, 0);
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search_back:
                finish();
                break;
            case R.id.search_text:
                if(!search_editText.getText().toString().equals("")){
                    saveKey(search_editText.getText().toString());
                    Bundle bundle = new Bundle();
                    bundle.putString("keyword",search_editText.getText().toString());
                    Intent intent = new Intent(SearchActivity.this,SearchResultActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else{
                    return;
                }

                break;
            case R.id.search_lajitong:
                dialog();
                break;
        }
    }
    public void dialog(){
//        AlertDialog.Builder builder = new AlertDialog.Builder(SearchActivity.this);
//        builder.setIcon(R.drawable.toutiao);
//        builder.setTitle("提示");
//        builder.setMessage("确定删除历史记录吗？");
//        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
//        {
//            @Override
//            public void onClick(DialogInterface dialog, int which)
//            {
//                delete();
//            }
//        });
//        //    设置一个NegativeButton
//        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
//        {
//            @Override
//            public void onClick(DialogInterface dialog, int which)
//            {
//
//            }
//        });
        //builder.show();
        MyAlertDialog myAlertDialog = new MyAlertDialog(this).builder()

                .setTitle("确认吗？")
                .setMsg("删除历史记录")
                .setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        delete();
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                });
        myAlertDialog.show();
    }
    public void delete(){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.deleteHistory();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200&&obj.has("data")){
                    Toasty.success(SearchActivity.this,"删除成功",Toasty.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: 请求失败");
            }
        });
    }
    public void getKeyData(){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getKeyByType(1);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200&& obj.has("data")){
                    JsonArray data = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    list = gson.fromJson(data,new TypeToken<ArrayList<Key>>(){}.getType());
                    listNew = new ArrayList<>();
                    int position[] = {};
                    position = Util.randomCommon(0,list.size()-1,4);
                    for(int i = 0;i<position.length;i++){
                        listNew.add(list.get(position[i]));
                    }
                    gridView_baseAdapter = new GridView_BaseAdapter(listNew);
                    search_gridview1.setAdapter(gridView_baseAdapter);
                    search_gridview1.setOnItemClickListener(new AdapterView.OnItemClickListener(){

                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            TextView tv = view.findViewById(R.id.item_key);
                            search_editText.setText("");
                            search_editText.setText(tv.getText().toString());
                            saveKey(tv.getText().toString());
                            Bundle bundle = new Bundle();
                            bundle.putString("keyword",tv.getText().toString());
                            Intent intent = new Intent(SearchActivity.this,SearchResultActivity.class);
                            intent.putExtras(bundle);
                            overridePendingTransition(0,0);
                            startActivity(intent);
                        }
                    });
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: 请求失败");
            }
        });
    }
    public void getKeyData2(){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getKeyByType(2);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200&& obj.has("data")){
                    JsonArray data = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    list2 = gson.fromJson(data,new TypeToken<ArrayList<Key>>(){}.getType());
                    ListNew2 = new ArrayList<>();
                    //int position[] = {};
                    //position = Util.randomCommon(0,list.size()-1,4);
                    if(list2.size()>=4){
                        for(int i = 0;i<4;i++){
                            ListNew2.add(list2.get(i));
                        }
                    }else{
                        for(int i = 0;i<list2.size();i++){
                            ListNew2.add(list2.get(i));
                        }
                    }

                    gridView_baseAdapter2 = new GridView_BaseAdapter(ListNew2);
                    //gridView_baseAdapter.notifyDataSetChanged();
                    search_gridview2.setAdapter(gridView_baseAdapter2);
                    search_gridview2.setOnItemClickListener(new AdapterView.OnItemClickListener(){
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            TextView tv = view.findViewById(R.id.item_key);
                            search_editText.setText("");
                            search_editText.setText(tv.getText().toString());
                            saveKey(tv.getText().toString());
                            Bundle bundle = new Bundle();
                            bundle.putString("keyword",tv.getText().toString());
                            Intent intent = new Intent(SearchActivity.this,SearchResultActivity.class);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    });
                    if(list2.size()>4){
                        search_xiala.setOnClickListener(new View.OnClickListener(){
                            @Override
                            public void onClick(View v) {
                                if(flag2 ){
                                    List<Key> extraList = new ArrayList<>();
                                    for(int i = 4;i<list2.size();i++){
                                        extraList.add(list2.get(i));
                                    }
                                    ListNew2.addAll(extraList);
                                    gridView_baseAdapter2.notifyDataSetChanged();
                                    Typeface font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
                                    search_xiala.setTypeface(font);
                                    search_xiala.setText(getResources().getString(R.string.shangla));
                                    flag2 = false;
                                }else{
                                    List<Key> extraList2 = new ArrayList<>();
                                    for(int i = 0;i<4;i++){
                                        extraList2.add(list2.get(i));
                                    }
                                    ListNew2.clear();
                                    ListNew2.addAll(extraList2);
                                    gridView_baseAdapter2.notifyDataSetChanged();
                                    Typeface font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
                                    search_xiala.setTypeface(font);
                                    search_xiala.setText(getResources().getString(R.string.xiala));
                                    flag2 = true;
                                }
                            }
                        });
                    }


                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: 请求失败");
            }
        });
    }
    public void getKeyData3(){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getKeyByType(3);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200&& obj.has("data")){
                    JsonArray data = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    list3 = gson.fromJson(data,new TypeToken<ArrayList<Key>>(){}.getType());
                    listNew3 = new ArrayList<>();
                    int position[] = {};
                    position = Util.randomCommon(0,list3.size()-1,8);
                    for(int i = 0;i<position.length;i++){
                        listNew3.add(list3.get(position[i]));
                    }
                    gridView_baseAdapter3 = new GridView_BaseAdapter(listNew3);
                    //gridView_baseAdapter.notifyDataSetChanged();
                    search_gridview3.setAdapter(gridView_baseAdapter3);
                    search_gridview3.setOnItemClickListener(new AdapterView.OnItemClickListener(){
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            TextView tv = view.findViewById(R.id.item_key);
                            search_editText.setText("");
                            search_editText.setText(tv.getText().toString());
                            saveKey(tv.getText().toString());
                            Bundle bundle = new Bundle();
                            bundle.putString("keyword",tv.getText().toString());
                            Intent intent = new Intent(SearchActivity.this,SearchResultActivity.class);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    });
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: 请求失败");
            }
        });
    }
    public void saveKey(String key){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.saveKey(key,2);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200){
                    Log.i(TAG, "onResponse: 保存成功");
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onResponse: 请求成功");
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
    }
}
